package com.zhgxi.zf.util;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	// 限制文件的上传大小
	private static final long maxFileSize = 104857600;

	protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html; charset=UTF-8");
		try {
			PrintWriter out = response.getWriter();
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(4096);
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setSizeMax(maxFileSize);
			upload.setHeaderEncoding("UTF-8");
			List<?> fileItems = upload.parseRequest(request);
			Iterator<?> iter = fileItems.iterator();
			String filePath = "";
			// 依次处理每一个文件：
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (!item.isFormField()) {
					String fileName = item.getName();
					long fileSize = item.getSize();
					if (fileName != null && fileName.trim().length() > 0 && fileSize < maxFileSize) {
						File dir = new File(getServletContext().getRealPath("upload/files/"));
						if (!dir.exists()) {
							dir.mkdirs();
						}
						filePath = "upload/files/" + new Date().getTime() + fileName.substring(fileName.indexOf("."));
						File uploadFile = new File(getServletContext().getRealPath(filePath));
						item.write(uploadFile);
					}
				}
			}
			out.print(filePath);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
